#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import  os, sys
os.environ["DJANGO_SETTINGS_MODULE"]="assoce.settings"
_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(_dir, '..', '..'))

from assoce.core.models import Emprunt
from assoce.notif.models import *
from datetime import datetime, timedelta
from mail import sendmail

def emprunt_statut(emprunt):
    if (emprunt.start + timedelta(days=14)) < datetime.now():
        return 1
    return 0

q = Emprunt.objects.filter(end__isnull=True, item__activite__label='BD')
depassements = {}
for e in q:
    if emprunt_statut(e) > 0:
        uname = e.membre.user.username
        if not depassements.has_key(uname): depassements[uname] = {'user':e.membre.user, 'list':[]}
        depassements[uname]['list'].append(e)

mail_depasst = MailTemplate.objects.get(name='depassement 1')
for item in depassements.values():
    sendmail(item['user'], mail_depasst, {'emprunts':item['list']})
    flag, c = Flag.objects.get_or_create(user=item['user'], name='depassement 1')
    if not c: flag.save()
